<template>
  <view class="weather-page">
    <button @click="getQuanzhouWeather">获取泉州天气预报</button>
    <view v-if="weatherInfo" class="weather-info">
      <view>城市：泉州</view>
      <view>日期：{{ weatherInfo.current_date }}</view>
      <view>当前温度：{{ weatherInfo.current_temp }}℃</view>
      <view>天气状况：{{ weatherInfo.current_condition }}</view>
      <view>明天天气：{{ weatherInfo.tomorrow_weather }}, {{ weatherInfo.tomorrow_temp_range }}</view>
    </view>
    <view v-if="errorMsg" class="error-tip">{{ errorMsg }}</view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
const weatherInfo = ref(null);
const errorMsg = ref('');

const getQuanzhouWeather = () => {
  weatherInfo.value = null;
  errorMsg.value = '';
  uni.showLoading({ title: '获取中...' });

  const currentDate = new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-');

  uni.request({
    url: 'https://wttr.in/泉州?format=j1',
    method: 'GET',
    timeout: 10000,
    success: (res) => {
      if (res.statusCode === 200) {
        const data = res.data;
        weatherInfo.value = {
          current_date: currentDate,
          current_temp: data.current_condition[0].temp_C,
          current_condition: data.current_condition[0].weatherDesc[0].value,
          tomorrow_weather: data.weather[1].hourly[0].weatherDesc[0].value,
          tomorrow_temp_range: `${data.weather[1].mintempC}℃~${data.weather[1].maxtempC}℃`
        };
      } else {
        errorMsg.value = `接口错误：服务器异常`;
      }
    },
    fail: (err) => {
      console.error('请求失败：', err);
      errorMsg.value = `网络异常：请检查网络连接`;
    },
    complete: () => {
      uni.hideLoading();
    }
  });
};
</script>

<style scoped>
.weather-page {
  padding: 30rpx;
}
.weather-info {
  margin-top: 20rpx;
  line-height: 2;
  background: #f5f5f5;
  padding: 20rpx;
  border-radius: 10rpx;
}
.error-tip {
  margin-top: 20rpx;
  color: #f30;
  font-size: 28rpx;
  line-height: 1.5;
}
button {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background: #007aff;
  color: #fff;
  border-radius: 10rpx;
}
</style>